package com.example.idlefish.MyAccount.activity

import android.annotation.SuppressLint
import android.os.*
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.*
import com.example.idlefish.GoodsInfo.ActivityContract.GooddResultContract
import com.example.idlefish.MyAccount.contract.HomepageContract
import com.example.idlefish.MyAccount.pojo.GoodWithUser
import com.example.idlefish.MyAccount.pojo.GoodWithUserResult
import com.example.idlefish.MyAccount.pojo.ResponseCode
import com.example.idlefish.MyAccount.pojo.RestResponse
import com.example.idlefish.MyAccount.pojo.UserHomepageInfo
import com.example.idlefish.MyAccount.pojo.Utils
import com.example.idlefish.PublicModule.ApplicationConst
import com.example.idlefish.PublicModule.CommonUtil
import com.example.idlefish.PublicModule.NetworkSettings
import com.example.idlefish.PublicModule.UserConst
import com.example.idlefish.PublicModule.UserConst.Companion.id
import com.example.idlefish.databinding.MyaccountCollectionBinding
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class MeCollectionActivity : AppCompatActivity() {
    private lateinit var binding: MyaccountCollectionBinding
    private var index = -1
    private var position = -1
    private val client = OkHttpClient()
    private val handler = Handler(Looper.getMainLooper())
    private val mediaType = "application/json;charset=utf-8".toMediaTypeOrNull()
    private val message = Message()
    private val mapper = ObjectMapper()
    private var meCollectionGoodsList = ArrayList<GoodWithUser>()
    private var adapter = MeCollectionAdapter(meCollectionGoodsList)

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        binding = MyaccountCollectionBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(findViewById(R.id.toolbar))
        supportActionBar?.setDisplayHomeAsUpEnabled(true);// 添加默认的返回图标
        supportActionBar?.setHomeButtonEnabled(true); // 设置返回键可用

        /* val userInfo =
            CommonUtil.getSerializable(intent, "userHomepageInfo", UserHomepageInfo::class.java)
 */
        binding.loading.show()

        // 列表
        // initList(userInfo.mySoldIds)
        initList(UserConst.id)

        setSupportActionBar(binding.toolbar)

        val layoutManager = LinearLayoutManager(this)
        binding.collectionList.layoutManager = layoutManager
        binding.collectionList.adapter = adapter

    }



    private fun initList(id: Long) {

        try {
            val request = Request.Builder().url(NetworkSettings.USER + "queryMeCollectionList?id=${id}")
                .get().build()

            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    message.what = ResponseCode.REQUEST_FAILED
                    handler.post {
                        Utils.showMessage(applicationContext, message)
                    }
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    val gson = Gson()
                    val responseData = response.body?.string()
                    val data = gson.fromJson(responseData, GoodWithUserResult::class.java)
                    Log.i("查看我收藏的", data.data.toString())
                    val info = data.data

                    handler.post {

                        if (info != null) {
                            meCollectionGoodsList.addAll(info)
                        }
                        adapter.notifyDataSetChanged()
                        binding.loading.hide()
                        Log.i("收藏列表", "$meCollectionGoodsList")
                    }
                }
            })
        } catch (e: Exception) {
            message.what = ResponseCode.JSON_SERIALIZATION
            Log.i("捕获异常", message.toString())
            e.printStackTrace()
        }
        binding.loading.hide()
    }

    private val homepageLauncher = registerForActivityResult(HomepageContract()) { result ->

    }

    private val goodContentLauncher = registerForActivityResult(GooddResultContract()){ result->

    }

    private inner class MeCollectionAdapter(private val mySoldList: ArrayList<GoodWithUser>) :
        RecyclerView.Adapter<MeCollectionAdapter.ViewHolder>() {
        // 创建ViewHolder实例，我们在这个方法中将elem布局加载进来，
        // 创建一个ViewHolder实例，并把加载出来的布局传入构造函数当中，最后将ViewHolder的实例返回。
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.myaccount_collection_elem, parent, false)
            val viewHolder = ViewHolder(view)

            // 单击元素
            viewHolder.itemView.setOnClickListener {
                val position = viewHolder.absoluteAdapterPosition
                val goodInfo = mySoldList[position]
                index = position

                goodContentLauncher.launch(goodInfo.goodId)
            }

            // 删除
            viewHolder.deleteButton.setOnClickListener {
                position = viewHolder.absoluteAdapterPosition
                delete(meCollectionGoodsList[position].goodId)
                meCollectionGoodsList.removeAt(position)
                notifyItemRemoved(position)
            }
            return viewHolder
        }

        // RecyclerView 子项的最外层布局
        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val avatar: ImageView = view.findViewById(R.id.myCollection_avatar)
            val nickname: TextView = view.findViewById(R.id.myCollection_poster)

            val image: ImageView = view.findViewById(R.id.myCollection_image)
            val info: TextView = view.findViewById(R.id.myCollection_info)
            val price: TextView = view.findViewById(R.id.myCollection_price)

            val talkButton: Button = view.findViewById(R.id.myCollection_talk)
            val deleteButton: Button = view.findViewById(R.id.myCollection_delete)
        }

        // 对 RecyclerView 子项的数据进行赋值，会在每个子项被滚动到屏幕内的时候执行
        // 通过 position参数得到当前项的info实例，然后再将数据设置到ViewHolder的TextView当中即可
        @SuppressLint("SetTextI18n")
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val good = mySoldList[position]
            holder.info.text = good.info
            holder.price.text = "¥${good.price}"
            holder.image.setImageBitmap(ApplicationConst.decodeBase64ToImage(applicationContext, good.pic))
            holder.avatar.setImageBitmap(ApplicationConst.decodeBase64ToImage(applicationContext, good.avatar))
            holder.nickname.text = good.nickname
/*             // 卖家
            holder.avatar.setImageBitmap(
                ApplicationConst.decodeBase64ToImage(
                    applicationContext,
                    good.avatar
                )
            )
            holder.nickname.text = good.nickname

            // 商品
            if (good.pic != null) {
                holder.image.setImageBitmap(
                    ApplicationConst.decodeBase64ToImage(
                        applicationContext,
                        good.pic
                    )
                )
            } else {
                holder.image.setImageResource(R.drawable.default_image)
            }
            holder.info.text = good.info
            holder.price.text = "¥${good.price}" */

        }

        override fun getItemCount() = mySoldList.size


    }

    private fun delete(goodId: Long) {
        try {
            val request = Request.Builder()
                .url("${NetworkSettings.COLLECTION}?goodId=$goodId&userId=$id")
                .delete().build()
            Log.i("删除收藏", request.url.toString())
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    message.what = ResponseCode.REQUEST_FAILED
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    if (response.isSuccessful) {
                        val body = response.body
                        if (body != null) {
                            val restResponse = mapper.readValue(
                                body.string(), RestResponse::class.java
                            )
                            message.what = restResponse.code
                        } else {
                            message.what = ResponseCode.EMPTY_RESPONSE
                            Log.e(
                                "RESPONSE_BODY_EMPTY", response.message
                            )
                        }
                    } else {
                        message.what = ResponseCode.SERVER_ERROR
                        Log.e("SERVER_ERROR", response.message)
                    }
                    handler.post {
                        // Utils.showMessage(applicationContext, message)
                    }
                }
            })
        } catch (e: Exception) {
            message.what = ResponseCode.JSON_SERIALIZATION
            // Utils.showMessage(applicationContext, message)
            e.printStackTrace()
        }
    }


}